﻿using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Text.Unicode;
using System.Threading.Tasks;

namespace WindowsFormsApp.utils
{
    public class UrlConvertUtil
    {

        private static Dictionary<string, string> projectIdMap = new Dictionary<string, string>();

        private static Dictionary<string, string> projectTokenMap = new Dictionary<string, string>();

        private static Dictionary<string, string> envTokenMap =  new Dictionary<string, string>();

        private static Dictionary<string, string> envExeMapBody = new Dictionary<string, string>();

        private static Dictionary<string, string> envExeMapHead = new Dictionary<string, string>();

        private static Dictionary<string, string> envPreUrlMap = new Dictionary<string, string>();

        static Logger logger = LogManager.GetCurrentClassLogger();
        static UrlConvertUtil() {
            InitData();
        }

        /*
         * 初始化数据
         */
        private static void InitData() {
            // 项目id
            projectIdMap.Add("zztx_dh_pc", "124");
            projectIdMap.Add("billservice", "148");
            projectIdMap.Add("customerservice", "137");
            projectIdMap.Add("financeservice", "342");
            projectIdMap.Add("goodsservice", "120");
            projectIdMap.Add("imexportservice", "340");
            projectIdMap.Add("saassystemsetting", "247");
            projectIdMap.Add("StatisticsService", "222");
            projectIdMap.Add("zztx_crm_pc", "126");
            projectIdMap.Add("zztx_ms_pc", "360");
            projectIdMap.Add("web-platform", "119");
            projectIdMap.Add("supplierservice", "384");
            // 项目token
            projectTokenMap.Add("zztx_dh_pc", "H3nS2pqK7PhnSC5VGyy9");
            projectTokenMap.Add("billservice", "Ydw-dyNASgDPygeu7mgc");
            projectTokenMap.Add("customerservice", "fDgyZtxVHJsANQp1wbZo");
            projectTokenMap.Add("financeservice", "YHvE79tQ5mKvxayqwMzR");
            projectTokenMap.Add("goodsservice", "gCyeFzto4hoRNUrECVRd");
            projectTokenMap.Add("imexportservice", "cPFp2gp_ejYHWwX6-K2Z");
            projectTokenMap.Add("saassystemsetting", "tc5ZsE93Vh2xETi9CV-j");
            projectTokenMap.Add("StatisticsService", "K5WgE-_MMTArPgcFgkLH");
            projectTokenMap.Add("zztx_crm_pc", "egvpU4hyoTmDyVZDYUn8");
            projectTokenMap.Add("zztx_ms_pc", "zGWe_T4NiwiUtsR96RkL");
            projectTokenMap.Add("web-platform", "9f7ngZcPjGErzqX9_29h");
            projectTokenMap.Add("supplierservice", "mQn_LKGeyDdB3suARa5-");

            envPreUrlMap.Add("dev", "https://dev-hdsaas.facehand.cn/gateway");
            envPreUrlMap.Add("fat", "https://fat-hdsaas.facehand.cn/gateway");
            envPreUrlMap.Add("pre", "https://pre-hdsaas.facehand.cn/gateway");
            envPreUrlMap.Add("pre_temp", "https://pre-hdsaas.facehand.cn/gateway");
            envPreUrlMap.Add("uat", "https://c.handday.com/gateway");
            envPreUrlMap.Add("prod", "https://c.handday.com/gateway");

            //token获取地址
            envTokenMap.Add("dev", "https://dev-hdsaas.facehand.cn/gateway/oauth-service/oauth/token?wxCorpId=wpc7diCwAAI0KNCMvlAbcB4xslzyzS8Q&wxUserId=woc7diCwAAyoPU6R59iAwE_UGz6Vrjfw&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000000");
            envTokenMap.Add("fat", "https://fat-hdsaas.facehand.cn/gateway/oauth-service/oauth/token?wxCorpId=wpc7diCwAAiaTTafQCtv7InNcTHq3IJQ&wxUserId=woc7diCwAARFkcBBSPX8uL8rRHag4V8g&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150007745");
            envTokenMap.Add("pre", "https://pre-hdsaas.facehand.cn/gateway/oauth-service/oauth/token?wxCorpId=wpc7diCwAAiaTTafQCtv7InNcTHq3IJQ&wxUserId=woc7diCwAARFkcBBSPX8uL8rRHag4V8g&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000022");
            envTokenMap.Add("pre_temp", "https://pre-hdsaas.facehand.cn/gateway/oauth-service/oauth/token?wxCorpId=wpc7diCwAAiaTTafQCtv7InNcTHq3IJQ&wxUserId=woc7diCwAARFkcBBSPX8uL8rRHag4V8g&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000022");
            envTokenMap.Add("uat", "https://c.handday.com/gateway/oauth-service/oauth/token?wxCorpId=wppVVJEQAAaLJvawFRJrqFJwH3ZxzHGw&wxUserId=wopVVJEQAA98nZMkA0I8OLMtrP-F9t8A&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000010");
            envTokenMap.Add("prod", "https://c.handday.com/gateway/oauth-service/oauth/token?wxCorpId=wppVVJEQAAaLJvawFRJrqFJwH3ZxzHGw&wxUserId=wopVVJEQAA98nZMkA0I8OLMtrP-F9t8A&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000010");
            //执行接口
            //动态表头

            envExeMapHead.Add("saveHeadUrl", "/systemsetting/api/v1/searchField/saveCategoryConfig");
            envExeMapHead.Add("queryHeadUrl", "/systemsetting/api/v1/searchField/queryDefaultConfig");

            //列配置
            envExeMapBody.Add("saveBodyUrl", "/goodsservice/api/v1/system/field/batchUpdate");
            envExeMapBody.Add("queryBodyUrl", "/goodsservice/api/v1/setting/filed/list");
        }

        /*
         * 查询到项目id
         */
        private static string getProjectId(String url)
        {
            foreach (KeyValuePair<String, String> entry in projectIdMap)
            {
                if (url.Contains(entry.Key))
                {
                    return entry.Value;
                }
            }
            throw new Exception("未查询到项目id");
        }

        /*
         * 查询到项目Token
         */
        private static string getProjectToken(String url)
        {
            foreach (KeyValuePair<String, String> entry in projectTokenMap)
            {
                if (url.Contains(entry.Key))
                {
                    return entry.Value;
                }
            }
            throw new Exception("未查询到项目Token");
        }


        /*
         * 查询到项目分支
         */
        private static string getBranch(String url)
        {
            int startIndex = url.IndexOf("/blob/") + "/blob/".Length;
            int endIndex = url.IndexOf("/src");
            return url.Substring(startIndex, endIndex- startIndex);
        }


        /*
         * 获取路径
         */
        private static string getFilepath(String url)
        {
            int startIndex = url.IndexOf("src/");
            return url.Substring(startIndex);
        }

        /*
         * 判断是列配置还是动态表头
         */
        private static bool isBodyField(String url)
        {
            return !url.Contains("front-end");
        }


        /**
        * 转换Json
        */
        public static async Task<string> convertUrl(string url, string inputBranch, string version)
        {

            string projectId = null;
            string branch = null;
            string filepath = null;
            // 替换为你的 GitLab Personal Access Token
            string token = null;
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    return "请输入需要转换的数据";
                }

                if (string.IsNullOrEmpty(version))
                {
                    return "请输入字段版本号";
                }

                if (string.IsNullOrEmpty(inputBranch))
                {
                    return "请输入执行分支";
                }
                // 获取项目id
                projectId = getProjectId(url);

                // 获取token
                token = getProjectToken(url);

                // 获取文件路径
                filepath = getFilepath(url);

                // 获取执行分支
                if (isBodyField(url))
                {
                    // 表体
                    branch = getBranch(url);
                }
                else
                {
                    // 表头
                    branch = inputBranch;
                }

                string configContent =await getConfigContentAsync(projectId, branch, filepath, token);

                if (string.IsNullOrEmpty(configContent)) {
                    return "没有获取到数据";
                }

                var options = new JsonSerializerOptions
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs)
                };

                // 配置解析选项（跳过注释、允许尾随逗号）
                // 正则移除注释（支持 /* */ 和 //）
                string RemoveJsonComments(string input)
                {
                    return Regex.Replace(
                        input,
                        @"(/\*([\s\S]*?)\*/)|(//.*$)",
                        "",
                        RegexOptions.Multiline
                    );
                }
                configContent = RemoveJsonComments(configContent);


                if (isBodyField(url))
                {

                    JsonNode rootNode = JsonNode.Parse(configContent);
                    JsonArray jsonArray = rootNode.AsArray();
                    for (int i = 0; i < jsonArray.Count; i++)
                    {
                        var val = jsonArray[i].AsObject();
                        if (val.TryGetPropertyValue("fieldVersion", out var fieldVersion) && fieldVersion != null) 
                        {
                            val["fieldVersion"] = version; // 修改属性值
                        }  
                    }
                    return rootNode.ToJsonString(options);
                }
                else
                {
                    JsonNode rootNode = JsonNode.Parse(configContent);
                    rootNode["version"] = version;
                    return rootNode.ToJsonString(options);
                }
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
                return e.Message;
            }
        }

        /*
        * 获取代码
        */
        private static async Task<string> getConfigContentAsync(string projectId, string branch, string filepath, string token)
        {

            try
            {
                string encodedString = Uri.EscapeDataString(Uri.UnescapeDataString(filepath));
                string apiUrl = $@"https://gitlab.facehand.cn/api/v4/projects/{projectId}/repository/files/{encodedString}?ref={branch}";

                HttpHelper httpHelper = new HttpHelper();
                WebHeaderCollection headers = new WebHeaderCollection();
                headers.Add("PRIVATE-TOKEN", token);

                string result=await httpHelper.GetAsync(apiUrl, headers);

                // 输出文件内容
                Console.WriteLine("文件内容:\n" + result);
                var jsonDocument = JsonDocument.Parse(result);
                var rootElement = jsonDocument.RootElement;
              
                // 获取"data"中的第一个对象
                if (!rootElement.TryGetProperty("content", out JsonElement dataElement))
                {
                    return "";
                }
                return Encoding.UTF8.GetString(dataElement.GetBytesFromBase64());

            }
            catch (Exception e)
            {
                logger.Error(e.Message);
                throw e;
            }
        }


        /**
        * 获取请求接口的token
        *
        * @param env
        * @author ldh
        * @date 2025-06-13 15:33
        */
        public  static async Task<string>  getToken(string env)
        {
            HttpHelper httpHelper = new HttpHelper();
            string token = await httpHelper.PostJsonAsync(envTokenMap[env],"");
            if (string.IsNullOrEmpty(token))
            {
                return "";
            }
            JsonNode jsonNode = JsonNode.Parse(token);
            JsonObject jsonObject = jsonNode.AsObject();
            if (jsonObject.TryGetPropertyValue("data", out var data) && data != null)
            {
                return data["access_token"].ToString();
            }
            return "";
        }

        /**
         * 执行接口（动态表头和列配置）
         *
         * @param url
         * @param env
         * @param token
         * @param content
         * @author ldh
         * @date 2025-06-13 15:47
         */
        public  static async Task<string> submit(string url, string env, string token, string content, bool isUat)
        {
            try
            {
                string exeUrl = "";
                string rst = "";
                if (isBodyField(url))
                {
                    exeUrl = envPreUrlMap[env] + envExeMapBody["saveBodyUrl"];
                }
                else
                {
                    exeUrl = envPreUrlMap[env] + envExeMapHead["saveHeadUrl"];
                }
              
                if (string.IsNullOrEmpty(token))
                {
                    rst = "token为空";
                    return rst;
                }
                HttpHelper httpHelper = new HttpHelper();
                WebHeaderCollection headers = new WebHeaderCollection();
                headers.Add("Authorization", string.Format("Bearer {0}", token));
                if (isUat) {
                    headers.Add("hdsaas", "always");
                }

                rst = await httpHelper.PostJsonAsync(exeUrl, content, headers);
                Console.WriteLine("执行结果:\n" + rst);
                return rst;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return string.Format("执行失败：{0}", ex);
            }
        }


        /**
         * 执行接口（动态表头和列配置）
         *
         * @param url
         * @param env
         * @param token
         * @param content
         * @author ldh
         * @date 2025-06-13 15:47
         */
        public static async Task<string> query(string url, string env, string token, string content, bool isUat)
        {
            try
            {
                string exeUrl = "";
                string rst = "";
                if (string.IsNullOrEmpty(token))
                {
                    rst = "token为空";
                    return rst;
                }
                JsonNode rootNode = JsonNode.Parse(content);
                if (isBodyField(url))
                {
                    JsonArray jsonArray = rootNode.AsArray();
                    if (jsonArray.Count==0)
                    {
                        return "没获取到数据";
                    }
                    JsonObject jsonObjecct = jsonArray[0].AsObject();
                    string businessType = jsonObjecct["businessType"].ToString();
                    exeUrl = envPreUrlMap[env] + envExeMapBody["queryBodyUrl"]+ "?isReset=true&businessType="+ businessType;
                    HttpHelper httpHelper = new HttpHelper();
                    WebHeaderCollection headers = new WebHeaderCollection();
                    headers.Add("Authorization", string.Format("Bearer {0}", token));
                    if (isUat)
                    {
                        headers.Add("hdsaas", "always");
                    }
                    rst = await httpHelper.GetAsync(exeUrl, headers);
                }
                else
                {
                    JsonObject jsonObjecct= rootNode.AsObject();
                    string categoryKey = jsonObjecct["categoryKey"].ToString();
                    exeUrl = envPreUrlMap[env] + envExeMapHead["queryHeadUrl"];
                    HttpHelper httpHelper = new HttpHelper();


                    WebHeaderCollection headers = new WebHeaderCollection();
                    headers.Add("Authorization", string.Format("Bearer {0}", token));
                    if (isUat)
                    {
                        headers.Add("hdsaas", "always");
                    }
                    string body = "{\"categoryKey\":\"" + categoryKey + "\"}";
                    rst = await httpHelper.PostJsonAsync(exeUrl, body, headers);
                }
                Console.WriteLine("执行结果:\n" + rst);
                return rst;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return string.Format("执行失败：{0}", ex);
            }
        }
    }
}
